/**
 * @file simple_filter_engine.h
 * @brief Basic filter engine.
 */
#pragma once

#include "filters/filter_engine.h"

#include <shared_mutex>
#include <unordered_map>

class SimpleFilterEngine : public IFilterEngine {
 public:
    SimpleFilterEngine();
    ~SimpleFilterEngine() override = default;

    /// IFilterEngine interface implementation
    bool addRule(const FilterRule& rule) override;
    bool removeRule(uint32_t ruleId) override;
    bool updateRule(const FilterRule& rule) override;

    void setRules(const std::vector<FilterRule>& rules) override;
    std::vector<FilterRule> getRules() const override;

    FilterResult processPacket(const Packet& packet) override;

    FilterStats getStatistics() const override;
    void resetStatistics() override;

    void enable() override { m_enabled = true; }
    void disable() override { m_enabled = false; }
    bool isEnabled() const override { return m_enabled; }

    void setDefaultAction(FilterAction action) override { m_defaultAction = action; }
    FilterAction getDefaultAction() const override { return m_defaultAction; }

 private:
    void sortRulesByPriority();
    uint32_t generateRuleId();

    mutable std::shared_mutex m_rulesMutex;
    std::unordered_map<uint32_t, FilterRule> m_rules;
    /// @brief Lower values have higher priority (not id).
    std::vector<uint32_t> m_rulePriorityOrder;

    std::atomic<bool> m_enabled{true};
    FilterAction m_defaultAction{FilterAction::ACCEPT};

    mutable std::shared_mutex m_statsMutex;
    FilterStats m_stats;
    std::atomic<uint32_t> m_nextRuleId{1};
};